package com.ifox.hgx.spring.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * Copyright (C), 2017-2018, 成都艾弗克斯科技有限公司
 * Author:   hanguixian
 * Date:     2018/10/21 14:51
 * Description:
 */


//通过添加 @Aspect 注解声明一个 bean 是一个切面!
@Order(0)
@Aspect
@Component
public class LoggingAspect {

    @Pointcut("execution(public int com.ifox.hgx.spring.aop.*.*(..))")
    public void declareJointPointExpression(){}

    //前置通知, 在方法执行之前执行
    //@Before 表示在目标方法执行之前执行 @Before 标记的方法的方法体.
    //@Before("execution(public int com.ifox.hgx.spring.aop.ArithmeticCalculator.add(int,int))")
    @Before("declareJointPointExpression()")
    public void beforeMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println("The method" + methodName + " begins" + args);
    }

    @After("execution(* com.ifox.hgx.spring.aop.*.*(..))")
    public void afterMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " ends");
    }

    @AfterReturning(value = "execution(* com.ifox.hgx.spring.aop.*.*(..))", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " afterReturning with " + result);
    }

    @AfterThrowing(value = "execution(* com.ifox.hgx.spring.aop.*.*(..))", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Exception ex) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " afterThrowing with " + ex);
    }

    @AfterThrowing(value = "execution(* com.ifox.hgx.spring.aop.*.*(..))", throwing = "ex")
    public void afterThrowingNull(JoinPoint joinPoint, NullPointerException ex) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " afterThrowing NullPointerException " + ex);
    }

}
